package com.mc2.docapp.disabilityassessmenttool;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mc2.docapp.disabilityassessmenttool.LowerLimb.LLCustDataType;
import com.mc2.docapp.disabilityassessmenttool.LowerLimb.Lower_Limb_MobStab_ExtraPoints;
import com.mc2.docapp.disabilityassessmenttool.Misc.InputFilterMinMax;
import com.mc2.docapp.disabilityassessmenttool.utils.MailerObject;
import com.mc2.docapp.disabilityassessmenttool.utils.SendMailTLS;

import java.util.HashSet;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.getEditTexts;
import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.router;


public class LowLimCombMobStabExtPoints extends Activity {

    private static final int id = Activities.LOWER_LIMB_MOB_STAT_EXT_POINTS;

    EditText extraPointsLEFT;
    EditText extraPointsRIGHT;
    EditText shorteningLEFT;
    EditText shorteningRIGHT;
    public Lower_Limb_MobStab_ExtraPoints lowerLimbMobStabExtraPoints = new Lower_Limb_MobStab_ExtraPoints();
    //db instance
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_low_lim_comb_mob_stab_ext_points);

        extraPointsLEFT  = (EditText) findViewById(R.id.extraPointsLEFT);
        extraPointsRIGHT = (EditText) findViewById(R.id.extraPointsRIGHT);
        shorteningLEFT = (EditText) findViewById(R.id.shorteningLEFT);
        shorteningRIGHT = (EditText) findViewById(R.id.shorteningRIGHT);
        initRealmDB();
        loadPrevData();
        sanitizeInput();

        Button saveNnextButton = (Button) findViewById(R.id.saveAndNext);
        saveNnextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                lowerLimbMobStabExtraPoints.setExtraPoints(new LLCustDataType(Integer.parseInt(IfNull(extraPointsRIGHT.getText().toString(), "0")),
                        Integer.parseInt(IfNull(extraPointsLEFT.getText().toString(), "0")), 0d, 0, 0));

                lowerLimbMobStabExtraPoints.setShorteningPoints(new LLCustDataType(Integer.parseInt(IfNull(shorteningRIGHT.getText().toString(), "0")),
                        Integer.parseInt(IfNull(shorteningLEFT.getText().toString(), "0")), 0d, 0, 0));

                lowerLimbMobStabExtraPoints.calc(lowerLimbMobStabExtraPoints);
                NewPatient.finalDto.getClass_lowerLimb_component().setLower_limb_mobStab_extraPoints(lowerLimbMobStabExtraPoints);
                //Calculate Total LL component
                double TotalLLComponentLEFT = NewPatient.finalDto.getClass_lowerLimb_component().getLower_limb_mobStab_extraPoints().getInner_calculations().getSummation_left()
                        + NewPatient.finalDto.getClass_lowerLimb_component().getCombMobStabCompLEFT();

                double TotalLLComponentRIGHT = NewPatient.finalDto.getClass_lowerLimb_component().getLower_limb_mobStab_extraPoints().getInner_calculations().getSummation_right()
                        + NewPatient.finalDto.getClass_lowerLimb_component().getCombMobStabCompRIGHT();


                NewPatient.finalDto.getClass_lowerLimb_component().setTotalLLComponentLEFT(TotalLLComponentLEFT);
                NewPatient.finalDto.getClass_lowerLimb_component().setTotalLLComponentRIGHT(TotalLLComponentRIGHT);

                lowerLimbMobStabExtraPoints.setId(id);
                realm.beginTransaction();
                realm.delete(Lower_Limb_MobStab_ExtraPoints.class);
                realm.insert(lowerLimbMobStabExtraPoints);
                realm.commitTransaction();
                try {
                    String str = new ObjectMapper().writeValueAsString(lowerLimbMobStabExtraPoints).toString();
//                    SendMailTLS.getMailer().sendMail(new MailerObject("saurab.hbhumkar@gmail.com", "MC2 Docapp", "str"));
                } catch (Exception e) {
                    System.out.println();
                }

                Intent intent = new Intent(LowLimCombMobStabExtPoints.this, router(LowLimCombMobStabExtPoints.class));
                startActivity(intent);




            }
        });

        Button clearAll = (Button) findViewById(R.id.clear);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashSet<EditText> views = new HashSet<>();
                getEditTexts((ViewGroup) findViewById(R.id.activity_main), views);
                for (EditText h : views)
                    h.setText("");
            }
        });

    }

    public String IfNull(String value, String defaultValue) {
        if(value == null || value.isEmpty()) {
            return defaultValue;
        } else {
            return  value;
        }
    }

    private void initRealmDB() {
        Realm.init(getApplicationContext());
        // realm = Realm.getDefaultInstance();
        RealmConfiguration config = new RealmConfiguration.Builder().name(id+".realm").build();
        realm = Realm.getInstance(config);
    }

    private void loadPrevData() {
        final RealmResults<Lower_Limb_MobStab_ExtraPoints> dtos = realm.where(Lower_Limb_MobStab_ExtraPoints.class).findAll();
//        .equalTo("id",id).findAll();
        System.out.println();
        try {
            //apply ui
            //
            //mapUI(new Lower_Limb_MobStab_ExtraPoints().strip(dtos.get(0)));
            //
            //realm.beginTransaction();
            //dtos.get(0).deleteFromRealm();
            //realm.commitTransaction();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            //no prev data found
        }
    }

    private void mapUI(Lower_Limb_MobStab_ExtraPoints oldData) {
        extraPointsLEFT.setText(String.valueOf((long) (oldData.getExtraPoints().getActual_left())));
        extraPointsRIGHT.setText(String.valueOf((long)(oldData.getExtraPoints()).getActual_right()));

        shorteningLEFT.setText(String.valueOf((long)(oldData.getShorteningPoints()).getActual_left()));
        shorteningRIGHT.setText(String.valueOf((long)(oldData.getShorteningPoints()).getActual_right()));

    }

    public void sanitizeInput() {
        extraPointsLEFT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});
        extraPointsRIGHT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "10")});

        shorteningLEFT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "100")});
        shorteningRIGHT.setFilters(new InputFilter[]{new InputFilterMinMax("0", "100")});
    }

}
